package com.thunbu.thunbu_meeting_system.activity

import com.cathu.lib_commonkt.base.BaseMVVMActivity
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.thunbu.lib_common.utils.ActivityManager
import com.thunbu.lib_common.utils.DeviceUtil
import com.thunbu.lib_common.utils.MFSPHelper
import com.thunbu.thunbu_meeting_system.MainActivity
import com.thunbu.thunbu_meeting_system.bean.CompanyInfo
import com.thunbu.thunbu_meeting_system.databinding.ActivityAuthorizationBinding
import com.thunbu.thunbu_meeting_system.databinding.ActivityLoginBinding
import com.thunbu.thunbu_meeting_system.dialog.CompanyCheckPop
import com.thunbu.thunbu_meeting_system.gotoActivity
import com.thunbu.thunbu_meeting_system.utils.AppUtils
import com.thunbu.thunbu_meeting_system.utils.SpUtils
import com.thunbu.thunbu_meeting_system.viewMdel.AuthorizationViewModel
import com.thunbu.thunbu_meeting_system.viewMdel.LoginViewModel

class LoginActivity:BaseMVVMActivity<ActivityLoginBinding, LoginViewModel>() {


    override fun onMVVMCreated() {
        ActivityManager.instance.finishAllBefore()
        initView()
        vm.userInfo.observe(this){
            AppUtils.setToken(it.userId)
            AppUtils.setUserInfo(it)
            gotoActivity<MainActivity> {  }
            finish()
        }
        vm.companysInfo.observe(this){
            showCheckCompanyPop(it)
        }
    }

    private fun initView() {
        bindViews.tvDeviceId.text = DeviceUtil.getDeviceId()
        bindViews.tvSubmit.setOnClickListener {
            val account = bindViews.etAccountNo.text.toString()
            val pwd = bindViews.etPassword.text.toString()
            if(account.isNullOrEmpty()){
                ToastUtils.show("请输入账号")
                return@setOnClickListener
            }
            if(pwd.isNullOrEmpty()){
                ToastUtils.show("请输入密码")
                return@setOnClickListener
            }
            vm.getCompanys(account)
        }
    }

    private fun showCheckCompanyPop(companysInfo:List<CompanyInfo>) {
        if(companysInfo.isNullOrEmpty()){
            ToastUtils.show("获取单位信息失败或没有单位信息")
            return
        }
        val account = bindViews.etAccountNo.text.toString()
        val pwd = bindViews.etPassword.text.toString()
        val pop = CompanyCheckPop(this,companysInfo){
            vm.doLogin(account, pwd,it)
        }
        XPopup.Builder(this).popupAnimation(PopupAnimation.NoAnimation)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asCustom(pop)
                .show()
    }
}